package com.le.tester.sevice.impl;

import com.le.tester.common.Const;
import com.le.tester.common.enums.RedisKey;
import com.le.tester.dao.ProductMapper;
import com.le.tester.entity.Product;
import com.le.tester.sevice.RedissonSecondKillService;
import com.le.tester.utils.DateTimeUtilFor8;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 描述：redisson分布式锁
 */
@Service
public class RedissonSecondKillServiceImpl implements RedissonSecondKillService {

    private static final Logger LOG = LoggerFactory.getLogger(RedissonSecondKillServiceImpl.class);

    @Autowired
    private RedissonClient redissonClient;

    @Resource
    private ProductMapper productMapper;

    public boolean doSecondKill(Long productId, Integer productQuantity) {
        String secondKillKey = RedisKey.DEC_STORE_LOCK.getCode() + Const.CONNECT_STR + productId;
        RLock lock = redissonClient.getLock(secondKillKey);
        lock.lock();
        try {
            Product product = productMapper.selectByPrimaryKey(productId);
            AtomicInteger atomicInteger = new AtomicInteger(product.getStockCount());
            if (atomicInteger.get() == 0) {
                LOG.info("库存为:{}", atomicInteger.get());
                return false;
            }
            //进行库存减少
            product.setStockCount(atomicInteger.decrementAndGet());
            productMapper.updateByPrimaryKey(product);
            LOG.info("秒杀成功：{},库存为：{}", DateTimeUtilFor8.time(), atomicInteger.get());
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            lock.unlock();
        }
        return true;
    }


}
